<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div class="release-idle-container">
                <div class="release-idle-container-title">发布闲置/公告</div>
                <div class="release-idle-container-form">
                    <el-input placeholder="请输入闲置/公告标题" v-model="idleItemInfo.idleName"
                              maxlength="30"
                              show-word-limit>
                    </el-input>
                    <el-input
                            class="release-idle-detiles-text"
                            type="textarea"
                            autosize
                            placeholder="请输入闲置/公告的详细介绍..."
                            v-model="idleItemInfo.idleDetails"
                            maxlength="1000"
                            show-word-limit>
                    </el-input>
                    <div class="release-idle-place">
                        <div class="release-tip">您的位置</div>
                        <el-cascader
                                :options="options"
                                v-model="selectedOptions"
                                @change="handleChange"
                                :separator="' '"
                                style="width: 90%;"
                        >
                        </el-cascader>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <div>
                            <div class="release-tip">闲置类别</div>
                            <el-select  v-model="idleItemInfo.idleLabel" placeholder="请选择类别">
                                <el-option
                                        v-for="item in options2"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </div>
                        <div v-show="idleItemInfo.idleLabel !== 5" style="width: 300px;">
                            <el-input-number v-model="idleItemInfo.idlePrice" :precision="2" :step="10" :max="10000000">
                                <div slot="prepend">价格</div>
                            </el-input-number>
                        </div>

                    </div>
                    <div class="release-idle-container-picture">
                        <div class="release-idle-container-picture-title">上传闲置照片</div>
                          <el-upload
                              class="upload-demo"
                              action="http://wmw-xyy.oss-cn-chengdu.aliyuncs.com"
                              :data="uploadPicData"
                              list-type="picture"
                              :before-upload="beforePicUpload"
                              :on-success="handlePicSuccess"
                              :limit="1"
                              :show-file-list="showFileList"
                              :on-exceed="handleExceed"
                              accept="image/*"
                              drag
                              multiple>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
                        </el-upload>
                        <div class="picture-list">
                            <el-image style="width: 600px;margin-bottom: 2px;" fit="contain"
                                      v-for="(img,index) in imgList" :src="img"
                                      :preview-src-list="imgList"></el-image>
                        </div>
                        <el-dialog :visible.sync="imgDialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </div>
                    <div style="display: flex;justify-content: center;margin-top: 30px;margin-bottom: 30px;">
                        <el-button type="primary" plain @click="releaseButton">确认发布</el-button>
                    </div>
                </div>
            </div>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppHeader.vue';
    import AppBody from '../common/AppPageBody.vue'
    import AppFoot from '../common/AppFoot.vue'
    import options from '../common/country-data.js'

    export default {
        name: "release",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                uploadPicData:{},
                imgDialogVisible:false,
                dialogImageUrl:'',
                showFileList:true,
                options:options,
                selectedOptions:[],
                options2: [{
                    value: 1,
                    label: '数码科技'
                }, {
                    value: 2,
                    label: '生活用品'
                }, {
                    value: 3,
                    label: '运动相关'
                }, {
                    value: 4,
                    label: '图书笔记'
                }, {
                    value: 5,
                    label: '公告展示'
                }],
                imgList:[],
                idleItemInfo:{
                    idleName:'',
                    idleDetails:'',
                    picture:'',
                    idlePrice:0,
                    idlePlace:'',
                    idleLabel:''
                },
            };
        },
        methods: {
          handlePicSuccess(res, file) {
            //上传的完整的文件地址 ： https://java1030.oss-cn-chengdu.aliyuncs.com/ymcc393olajewfjaolfja.jpg
            var urlPath = this.uploadPicData.host + '/' + this.uploadPicData.key.replace("${filename}",file.name) ;
            this.idleItemInfo.picture = urlPath;
            this.$message({message: '上传成功', type: 'success' });
          },
          async beforePicUpload(){
            await this.getSign(this.uploadPicData);
          },
          async getSign(data){
            //让这个请求变成同步请求
            await this.$http.get("/oss/sign").then(response=>{
              //设置相关的参数
              var resultObj = response.data.data;
              data.policy = resultObj.policy;
              data.signature = resultObj.signature;
              data.ossaccessKeyId = resultObj.accessid;
              data.dir = resultObj.dir;
              data.host = resultObj.host;
              //上传的文件名，使用UUID处理一下
              data.key = resultObj.dir + '/'+this.getUUID()+'_${filename}';
            });
          },
          getUUID() {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
              s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";
            var uuid = s.join("");
            return uuid;
          },
            handleChange(value) {
                console.log(value);
                this.idleItemInfo.idlePlace=value[1];
            },
            // fileHandleRemove(file, fileList) {
            //     console.log(file, fileList);
            //     for(let i=0;i<this.imgList.length;i++){
            //         if(this.imgList[i]===file.response.data){
            //             this.imgList.splice(i,1);
            //         }
            //     }
            // },
            // fileHandlePreview(file) {
            //     console.log(file);
            //     this.dialogImageUrl=file.response.data;
            //     this.imgDialogVisible=true;
            // },
            fileHandleSuccess(response, file, fileList){
                console.log("file:",response,file,fileList);
                this.imgList.push(response.data);
            },
            releaseButton(){
                // this.idleItemInfo.picture=JSON.stringify(this.imgList);
                console.log(this.idleItemInfo);
                if(this.idleItemInfo.idleName&&
                    this.idleItemInfo.idleDetails&&
                    this.idleItemInfo.idlePlace&&
                    this.idleItemInfo.idleLabel&&
                  (this.idleItemInfo.idlePrice || this.idleItemInfo.idleLabel === 5)){
                    this.$api.addIdleItem(this.idleItemInfo).then(res=>{
                        if (res.status_code === 1) {
                            this.$message({
                                message: '发布成功！',
                                type: 'success'
                            });
                            console.log(res.data);
                            this.$router.replace({path: '/details', query: {id: res.data.id}});
                        } else {
                            this.$message.error('发布失败！'+res.msg);
                        }
                    }).catch(e=>{
                        this.$message.error('请填写完整信息');
                    })
                }else {
                    this.$message.error('请填写完整信息！');
                }

            },
            handleExceed(files, fileList) {
                this.$message.warning(`限制10张图片，本次选择了 ${files.length} 张图，共选择了 ${files.length + fileList.length} 张图`);
            },
            isNotice() {

            }
        }
    }
</script>

<style scoped>
    .release-idle-container {
        min-height: 85vh;
    }

    .release-idle-container-title {
        font-size: 18px;
        padding: 30px 0;
        font-weight: 600;
        width: 100%;
        text-align: center;
    }

    .release-idle-container-form {
        padding: 0 180px;
    }

    .release-idle-detiles-text {
        margin: 20px 0;
    }
    .release-idle-place{
        margin-bottom: 15px;
    }
    .release-tip{
        color: #555555;
        float: left;
        padding-right: 5px;
        height: 36px;
        line-height: 36px;
        font-size: 14px;
    }
    .release-idle-container-picture{
        margin: 20px 0;

    }
    .release-idle-container-picture-title{
        margin: 10px 0;
        color: #555555;
        font-size: 14px;
    }
    .picture-list {
        margin: 20px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
</style>